using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Web.Services2;
using Microsoft.Web.Services2.Messaging;
using Microsoft.Web.Services2.Addressing;
using CSF.Communications.Sdp.ServiceLogic.Entities;
using CSF.Communications.Sdp.ServiceLogic.Exceptions;
using Microsoft.Web.Services2.Security.Tokens;
using System.Xml;


namespace CSF.Communications.Sdp.ServiceLogic.Interface
{
    /// <summary>
    /// Summary description for SoapUtility
    /// </summary>
    public class SoapUtility
    {
        public SoapUtility()
        {
        }

        #region SendRequest
        /// <summary>
        /// 
        /// </summary>
        /// <param name="SessionID"></param>
        /// <param name="RequestUUID"></param>
        /// <param name="CorrelationId"></param>
        /// <param name="body"></param>
        /// <param name="action"></param>
        public void SendRequest(SoapRequestState request, XmlDocument body, string action)
        {

            SoapEnvelope reqEnv;
            EndpointReference epr;
            SlClient ss;
            try
            {
                reqEnv = InsertSoapHeader(request.SessionID, request.RequestUUID, request.RequestUUID, request.FromAddress, request.ToAddress);
                reqEnv.Body.InnerXml = body.InnerXml.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");
                epr = new EndpointReference(request.FromAddress);
                ss = new SlClient(epr);
                ss.SendWSEOneWay(action, reqEnv);
            }
            catch (Exception ex)
            {
                throw new SDPWSEException(ex.Message);
            }

        }
        #endregion

        #region SendServicelogicResponse
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void SendServicelogicResponse(SoapRequestState request, ServiceLogicCompletionStatus response)
        {

            SoapEnvelope reqEnv;
            EndpointReference epr;
            SlClient ss;
            try
            {
                reqEnv = InsertSoapHeader(request.SessionID, request.RequestUUID, request.RequestUUID, request.FromAddress, request.ToAddress);
                reqEnv.SetBodyObject(response);
                epr = new EndpointReference(request.FromAddress);
                ss = new SlClient(epr);
                ss.SendWSEOneWay("ServiceLogicStatus", reqEnv);
            }
            catch (Exception ex)
            {
                throw new SDPWSEException(ex.Message);
            }

        }
        #endregion

        #region InsertSoapHeader
        /// <summary>
        /// 
        /// </summary>
        /// <param name=\"SessionId"></param>
        /// <param name="RequestUUID"></param>
        /// <param name="corelationId"></param>
        /// <param name="toUri"></param>
        /// <returns></returns>
        private SoapEnvelope InsertSoapHeader(string SessionId, string RequestUUID, string corelationId, Uri toUri, Uri fromUri)
        {
            SoapEnvelope envelope = null;
            XmlDocument xmlResponse = null;
            MessageID mesId = null;
            XmlDocument xdocu = null;
            XmlElement xele = null;
            From objFrom = null;
            ReplyTo objReplyTo = null;
            ReferenceProperties refProp = null;
            XmlDocument xDocRefProp = null;
            try
            {
                string primaryUserId = ConfigurationManager.AppSettings["TokenUserName"], primaryUserPassword = ConfigurationManager.AppSettings["TokenPassword"];
                envelope = new SoapEnvelope();
                xmlResponse = new XmlDocument();

                XmlElement soapHeader = envelope.CreateHeader();

                XmlDocument soapDoc = soapHeader.OwnerDocument;
                XmlElement customHeader = soapDoc.CreateElement("csfse", "SessionID", "http://www.microsoft.com/csf/20/Session/");
                customHeader.InnerXml = SessionId;
                soapHeader.AppendChild(customHeader);
                customHeader = soapDoc.CreateElement("RequestUUID");
                customHeader.InnerXml = RequestUUID;
                soapHeader.AppendChild(customHeader);

                mesId = new MessageID(new Uri("uuid:" + System.Guid.NewGuid().ToString()));
                xdocu = new XmlDocument();
                xele = mesId.GetXml(xdocu);

                xDocRefProp = new XmlDocument();
                xDocRefProp.LoadXml("<wsa:ReferenceProperties  xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/03/addressing\"><RequestUUID>" + corelationId + "</RequestUUID><csfse:CsfContext xmlns:csfse=\"http://www.microsoft.com/csf/20/Session/\" /></wsa:ReferenceProperties>");
                refProp = new ReferenceProperties(xDocRefProp.DocumentElement);
                objReplyTo = new ReplyTo(fromUri);
                objReplyTo.ReferenceProperties = refProp;


                objFrom = new From(fromUri);
                envelope.Context.Addressing.From = objFrom;
                envelope.Context.Addressing.ReplyTo = objReplyTo;
                envelope.Context.Addressing.MessageID.LoadXml(xele);


                

                envelope.Context.Security.Tokens.Add(new UsernameToken(primaryUserId, primaryUserPassword, PasswordOption.SendPlainText));

                return envelope;
            }
            catch (Exception insertSoapHeaderException)
            {
                throw new SDPWSEException(insertSoapHeaderException);

            }

        }
        #endregion

    }


}
